<!DOCTYPE html>
<html>
  <head>
    <title>Data Visualization!</title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
  </head>
  <body>
    <svg width="960" height="500" id="mainsvg" class="svgs"></svg>
    <script>
      const svg = d3.select('#mainsvg');
      const width = +svg.attr('width');
      const height = +svg.attr('height');
      const margin = {top: 20, right: 20, bottom: 20, left: 100};
      const innerWidth = width - margin.left - margin.right;
      const innerHeight = height - margin.top - margin.bottom;
      const xValue = (datum) => {return datum.population};
      const yValue = (datum) => {return datum.country};

      const render = function(data){

        // Linear Scale: Data Space -> Screen Space; 
        const xScale = d3.scaleLinear()
        .domain([0, d3.max(data, xValue)])
        .range([0, innerWidth]);

        // Introducing y-Scale; 
        const yScale = d3.scaleBand()
        .domain(data.map(yValue))
        .range([0, innerHeight])
        .padding(0.1);

        // The reason of using group is that nothing is rendered outside svg, so margin of svg is always blank while margin of group is rendered inside svg; 
        const g = svg.append('g')
        .attr('transform', `translate(${margin.left}, ${margin.top})`);

        // Do the data join (Enter)
        g.selectAll('rect')
        .data(data)
        .enter() 
        .append('rect')
        .attr('y', datum => yScale(yValue(datum)))
        .attr('width', (datum) => {return xScale(xValue(datum))}) // use xSacle to re-scale data space (domain) and return the rescaled population; 
        .attr('height', yScale.bandwidth())
        .attr('fill', 'steelblue')

        // Adding axes
        g.append('g').call(d3.axisLeft(yScale));
        g.append('g').call(d3.axisBottom(xScale))
        .attr('transform', `translate(${0}, ${innerHeight})`);
      }

      d3.csv('./static/data/population.csv')
      .then(function(data){
          data.forEach( datum => {
            //datum.population = parseFloat(datum.population);
            datum.population = +(datum.population);
          } )
          console.log(data);
          console.log(data.map( (datum) => {return datum.country; } ))
          render(data);
      });
    </script>
  </body>
</html>